package com.lm.common.log.aspect;

import com.alibaba.fastjson.JSON;
import com.lm.common.core.util.SpringContextHolder;
import com.lm.common.log.annotation.SysLog;
import com.lm.common.log.enums.BusinessStatus;
import com.lm.common.log.event.SysLogEvent;
import com.lm.upms.api.entity.SysOperLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 系统操作日志切面
 *
 * @author lm
 * @date 2019/6/19 16:28
 */
@Slf4j
@Aspect
@Component
public class SysOperLogAspect {

    /**
     * 定义controller切入点拦截规则，拦截SysLog注解的方法
     */
    @Pointcut("@annotation(com.lm.common.log.annotation.SysLog)")
    public void sysOperLogAspect() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint
     */
    @AfterReturning(pointcut = "sysOperLogAspect()")
    public void doAfterReturning(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "sysOperLogAspect()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e) {
        try {
            // 获得注解
            SysLog controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            Long startTime = System.currentTimeMillis();

            SysOperLog operLog = new SysOperLog();
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 处理设置注解上的参数
            Object[] args = joinPoint.getArgs();
            getControllerMethodDescription(controllerLog, operLog, args);
            Long endTime = System.currentTimeMillis();
            operLog.setExceTime((endTime - startTime));

            // 发布事件
            SpringContextHolder.publishEvent(new SysLogEvent(operLog));
        } catch (Exception ex) {
            // 记录本地异常日志
            log.error("前置通知异常，异常信息:{}", ex.getMessage());
            ex.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log
     * @param operLog
     * @param args
     * @throws Exception
     */
    public void getControllerMethodDescription(SysLog log, SysOperLog operLog, Object[] args) throws Exception {
        // 设置action动作
        operLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType().ordinal());
        // 操作时间
        operLog.setOperTime(LocalDateTime.now());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(operLog, args);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog
     * @param args
     * @throws Exception
     */
    private void setRequestValue(SysOperLog operLog, Object[] args) throws Exception {
        String params = JSON.toJSONString(args, true);
        operLog.setOperParam(StringUtils.substring(params, 0, 2000));
    }

    /**
     * 是否存在注解，如果存在就获取
     *
     * @param joinPoint
     * @return
     * @throws Exception
     */
    private SysLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(SysLog.class);
        }
        return null;
    }

}